<template>
  <video :id="id" autoplay muted></video>
</template>
<script>
import flvjs from 'flv.js'
import SrsRtcPlayerAsync from './utils/WebRTC'

export default {
  name: 'PlayerBox',
  props: {
    id: {
      type: String,
      default: 'player'
    },
    url: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      player: null,
      rtcRE: /^webrtc/i,
      flvRE: /.flv/i
    }
  },
  mounted () {
    if (this.flvRE.test(this.url)) {
      this.startPlayFlv()
    } else if (this.rtcRE.test(this.url)) {
      this.startPlayRTC()
    }
  },
  watch: {
    url (val) {
      if (this.flvRE.test(val)) {
        this.startPlayFlv()
      } else if (this.rtcRE.test(val)) {
        this.startPlayRTC()
      }
    }
  },
  methods: {
    // 播放flv
    startPlayFlv () {
      this.stopPlayer()
      this.player = flvjs.createPlayer({
        type: 'flv',
        url: this.url
      })
      this.player.attachMediaElement(document.getElementById(this.id))
      this.player.load()
      this.player.play()
    },
    // 停止播放器
    stopPlayer () {
      if (this.player) {
        try {
          this.player.destroy()
          this.player = null
        } catch (err) {
          this.player.close()
          this.player = null
        }
      }
    },
    // 播放webrtc
    startPlayRTC () {
      // Close PC when user replay.
      this.stopPlayer()
      const video = document.getElementById(this.id)
      this.player = new SrsRtcPlayerAsync()
      this.player.onaddstream = function (event) {
        // console.log('Start play, event: ', event)
        video.srcObject = event.stream
      }
      this.player.play(this.url)
    }
  }
}
</script>

<style scoped>
video {
  object-fit: fill;
  height: 100%;
  width: 100%;
}
</style>
